/*
 * :file description: 
 * :name: \redux_project\src\redux-visualizer\ReduxVisualizer.tsx
 * :author: linkeda
 * :copyright: (c) 2025, Tungee
 * :date created: 2025-08-28 11:46:36
 * :last editor: linkeda
 * :date last edited: 2025-08-28 11:53:52
 */
import React, { useState, useEffect } from 'react';
import { createStore, applyMiddleware } from './simpleRedux';
import type { Action, Reducer, Dispatch } from './simpleRedux';

// 定义可视化工具的状态类型
interface VisualizerState {
  count: number;
  todos: string[];
}

// 定义操作类型
type VisualizerAction = 
  | { type: 'INCREMENT' }
  | { type: 'DECREMENT' }
  | { type: 'ADD_TODO'; payload: string }
  | { type: 'REMOVE_TODO'; payload: number };

// 示例中间件 - 日志中间件
const loggerMiddleware = () => (next: Dispatch<Action>) => (action: Action) => {
  console.log('Middleware: Dispatching action:', action);
  const result = next(action);
  console.log('Middleware: New state after action:', result);
  return result;
};

// 示例中间件 - 延迟中间件
const delayMiddleware = () => (next: Dispatch<Action>) => (action: Action) => {
  setTimeout(() => {
    console.log('Middleware: Delayed action processed:', action);
  }, 500);
  return next(action);
};

// 创建示例reducer
const initialState: VisualizerState = {
  count: 0,
  todos: ['Learn Redux', 'Build something awesome']
};

const reducer: Reducer<VisualizerState, VisualizerAction> = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    case 'ADD_TODO':
      return { ...state, todos: [...state.todos, action.payload] };
    case 'REMOVE_TODO':
      return {
        ...state,
        todos: state.todos.filter((_, index) => index !== action.payload)
      };
    default:
      return state;
  }
};

// 创建示例store
const store = createStore(reducer, initialState, applyMiddleware(loggerMiddleware, delayMiddleware));

const ReduxVisualizer: React.FC = () => {
  const [state, setState] = useState<VisualizerState>(store.getState());
  const [newTodo, setNewTodo] = useState('');
  const [selectedMiddleware, setSelectedMiddleware] = useState<{ logger: boolean; delay: boolean }>({
    logger: true,
    delay: true
  });
  const [dispatchHistory, setDispatchHistory] = useState<{ action: Action; timestamp: string }[]>([]);
  const [isUsingCustomRedux, setIsUsingCustomRedux] = useState(true);

  // 订阅状态变化
  useEffect(() => {
    const unsubscribe = store.subscribe(() => {
      setState(store.getState() as VisualizerState);
    });

    return () => unsubscribe();
  }, [isUsingCustomRedux]);

  // 处理分发action
  const handleDispatch = (action: VisualizerAction) => {
    setDispatchHistory([
      ...dispatchHistory,
      { action, timestamp: new Date().toLocaleTimeString() }
    ]);
    store.dispatch(action);
  };

  // 添加新Todo
  const handleAddTodo = () => {
    if (newTodo.trim()) {
      handleDispatch({ type: 'ADD_TODO', payload: newTodo.trim() });
      setNewTodo('');
    }
  };

  // 移除Todo
  const handleRemoveTodo = (index: number) => {
    handleDispatch({ type: 'REMOVE_TODO', payload: index });
  };

  // 清除历史记录
  const clearHistory = () => {
    setDispatchHistory([]);
  };

  return (
    <div className="redux-visualizer">
      <h2>Redux 原理可视化工具</h2>
      
      {/* 配置区域 */}
      <div className="config-panel">
        <div className="config-item">
          <label>
            <input
              type="checkbox"
              checked={isUsingCustomRedux}
              onChange={(e) => setIsUsingCustomRedux(e.target.checked)}
            />
            使用自定义 Redux 实现
          </label>
        </div>
        
        <div className="config-item">
          <label>
            <input
              type="checkbox"
              checked={selectedMiddleware.logger}
              onChange={(e) => setSelectedMiddleware({...selectedMiddleware, logger: e.target.checked})}
            />
            启用日志中间件
          </label>
        </div>
        
        <div className="config-item">
          <label>
            <input
              type="checkbox"
              checked={selectedMiddleware.delay}
              onChange={(e) => setSelectedMiddleware({...selectedMiddleware, delay: e.target.checked})}
            />
            启用延迟中间件
          </label>
        </div>
      </div>

      {/* 状态展示区域 */}
      <div className="state-panel">
        <h3>当前状态 (State)</h3>
        <div className="state-content">
          <pre>{JSON.stringify(state, null, 2)}</pre>
        </div>
      </div>

      {/* Action 分发区域 */}
      <div className="action-panel">
        <h3>分发 Action</h3>
        
        <div className="action-group">
          <h4>计数器操作</h4>
          <button onClick={() => handleDispatch({ type: 'INCREMENT' })}>增加计数</button>
          <button onClick={() => handleDispatch({ type: 'DECREMENT' })}>减少计数</button>
        </div>
        
        <div className="action-group">
          <h4>待办事项操作</h4>
          <input
            type="text"
            value={newTodo}
            onChange={(e) => setNewTodo(e.target.value)}
            placeholder="输入新的待办事项..."
          />
          <button onClick={handleAddTodo}>添加 Todo</button>
        </div>
      </div>

      {/* Todo 列表 */}
      <div className="todo-panel">
        <h3>待办事项列表</h3>
        <ul>
          {state.todos.map((todo, index) => (
            <li key={index}>
              {todo} 
              <button onClick={() => handleRemoveTodo(index)}>删除</button>
            </li>
          ))}
        </ul>
      </div>

      {/* Action 历史记录 */}
      <div className="history-panel">
        <div className="history-header">
          <h3>Action 历史记录</h3>
          <button onClick={clearHistory}>清除历史</button>
        </div>
        <div className="history-content">
          {dispatchHistory.length === 0 ? (
            <p>暂无 Action 历史记录</p>
          ) : (
            <ul>
              {dispatchHistory.map((item, index) => (
                <li key={index}>
                  <div className="history-time">{item.timestamp}</div>
                  <div className="history-action">
                    <strong>Type:</strong> {item.action.type}
                    {item.action.payload !== undefined && (
                      <>, <strong>Payload:</strong> {JSON.stringify(item.action.payload)}</>
                    )}
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>

      {/* Redux 流程图解 */}
      <div className="flow-diagram">
        <h3>Redux 数据流图示</h3>
        <div className="flow-content">
          <div className="flow-node">
            <div className="node-title">React 组件</div>
            <div className="node-desc">dispatch(action)</div>
          </div>
          <div className="flow-arrow">→</div>
          <div className="flow-node">
            <div className="node-title">Action</div>
            <div className="node-desc">{dispatchHistory.length > 0 ? 
              JSON.stringify(dispatchHistory[dispatchHistory.length - 1].action) : 
              '{ type: "ACTION_TYPE", payload: data }'
            }</div>
          </div>
          <div className="flow-arrow">→</div>
          <div className="flow-node">
            <div className="node-title">Middleware</div>
            <div className="node-desc">logger, delay</div>
          </div>
          <div className="flow-arrow">→</div>
          <div className="flow-node">
            <div className="node-title">Reducer</div>
            <div className="node-desc">(state, action) {'=>'} newState</div>
          </div>
          <div className="flow-arrow">→</div>
          <div className="flow-node">
            <div className="node-title">Store</div>
            <div className="node-desc">保存更新后的状态</div>
          </div>
          <div className="flow-arrow">→</div>
          <div className="flow-node">
            <div className="node-title">React 组件</div>
            <div className="node-desc">重新渲染</div>
          </div>
        </div>
      </div>

      {/* Redux 核心概念说明 */}
      <div className="concepts-panel">
        <h3>Redux 核心概念</h3>
        <div className="concept-item">
          <h4>单向数据流</h4>
          <p>Redux 遵循严格的单向数据流，数据流动路径是确定的：Action → Reducer → Store → View。</p>
        </div>
        <div className="concept-item">
          <h4>Store</h4>
          <p>Store 是单一的数据源，包含了应用的整个状态树。通过 createStore 函数创建。</p>
        </div>
        <div className="concept-item">
          <h4>Actions</h4>
          <p>Actions 是描述发生了什么的纯对象，必须有一个 type 字段。</p>
        </div>
        <div className="concept-item">
          <h4>Reducers</h4>
          <p>Reducers 是纯函数，接收当前状态和一个 action，返回新的状态。</p>
        </div>
        <div className="concept-item">
          <h4>Middleware</h4>
          <p>Middleware 提供了扩展 dispatch 函数的能力，可以处理异步操作、日志记录等。</p>
        </div>
      </div>
    </div>
  );
};

export default ReduxVisualizer;